import { Init, Provide, Inject } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GameLevelInfoEntity } from '../entity/info';

/**
 * game模块-关卡信息
 */
@Provide()
export class GameLevelInfoService extends BaseService {
  @InjectEntityModel(GameLevelInfoEntity)
  gameLevelInfoEntity: Repository<GameLevelInfoEntity>;


  @Inject()
  ctx;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.gameLevelInfoEntity);
  }
  /**
    * 手机端获取关卡信息
    * @param param
    * @returns
    */
  async getLevels() {
    // 有id,就判断关卡有没有解锁
    let level = await this.nativeQuery(
      'select id,createTime,updateTime,name,type,levels,orderNum,nextLevel from game_level_info '
    );
    let list = []
    if (this.ctx?.user) {
      let deblocking = await this.nativeQuery(
        'select id,createTime,updateTime,levelId,playerId from game_level_player where playerId = ?',
        [this.ctx?.user.id]
      );
      level.forEach(item => {
        item.levels = JSON.parse(item.levels)
        if (item.type == 0) {
          let index = deblocking.findIndex(ret => ret.levelId == item.id)
          if (index == -1) {
            item.levels = []
          }
        }
        list.push(item)
      })
    } else {
      // 没有id,就返回试玩关卡,其他关卡也返回,但是没有关卡详情
      level.forEach(item => {
        item.levels = JSON.parse(item.levels)
        if (item.type == 0) {
          item.levels = []
        }
        list.push(item)
      })
    }
    return list
  }
  /**
    * 判断当前关卡有没有解锁
    * @param levelId    
    * @param playerId
    * @returns
    */
  async isDeblocking(levelId, playerId) {
    let deblocking = await this.nativeQuery(
      'select id,createTime,updateTime,levelId,playerId from game_level_player where playerId = ?',
      [playerId]
    );
    let detail=await this.gameLevelInfoEntity.findOneBy({id:levelId})
    let index=-1
    if(detail.type==1){
      index=0
    }else{
      index=deblocking.findIndex(item=>item.levelId == detail.id)
    }
    return {index,detail}
  }
  
  /**
    * 判断当前关卡有没有解锁
    * @param levelId    
    * @param playerId
    * @returns
    */
}
